package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserItemVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author liubo
 * @description 针对表【system_user(员工信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemUser>
        implements SystemUserService {

    @Override
    public IPage<SystemUserItemVo> pageQuerySystemUserItemVo(Page<SystemUserItemVo> systemUserItemVoPage, SystemUserQueryVo queryVo) {
        return baseMapper.pageQuerySystemUserItemVo(systemUserItemVoPage, queryVo);
    }

    @Override
    public Boolean isUsernameExists(String username) {
        LambdaQueryWrapper<SystemUser> systemUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        systemUserLambdaQueryWrapper.eq(SystemUser::getUsername, username);
        return this.count(systemUserLambdaQueryWrapper) > 0;
    }

    @Override
    public void updateStatusById(Long id, BaseStatus status) {
        LambdaUpdateWrapper<SystemUser> systemUserLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        systemUserLambdaUpdateWrapper.eq(SystemUser::getId, id).set(SystemUser::getStatus, status);
        this.update(systemUserLambdaUpdateWrapper);
    }

    @Override
    public SystemUserItemVo getUserItemVoById(Long id) {
        return baseMapper.getUserItemVoById(id);
    }

    @Override
    public void saveOrUpdateSystemUser(SystemUser systemUser) {
        // 判断密码是否为空
        if (StringUtils.hasText(systemUser.getPassword())) {
            // 不为空则更新密码 要注意这里用的是common.codec包的DigestUtils,不是spring的DigestUtils
            systemUser.setPassword(DigestUtils.sha256Hex(systemUser.getPassword()));
        }
    }
}




